import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as ContractQueryAction from '../actions/contractQuery';
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty';
import WeaFormmodeTop from './WeaFormmodeTop';

import ContractShare from './setting/contractShare'
import RelateCommunication from './customerCard/RelateCommunication.js'
import { WeaTable } from 'comsRedux';
import { WeaTab,WeaSearchGroup,WeaRightMenu} from 'ecCom';
import { WeaErrorPage, WeaTools,WeaDialog,WeaTableEdit,WeaReqTop,WeaBrowser,WeaScope   } from 'ecCom';
import { Button, Form, Modal, message,Table } from 'antd';
import Immutable from 'immutable'

import ContractPayTable from './WeaCrmTableEdit/contractPayTable'
import ContractInfo from './contract/ContractInfo'

const is = Immutable.is;
const WeaTableAction = WeaTable.action;
const createForm = Form.create;
const FormItem = Form.Item;
const { getComponent } = WeaTools;


class ContractQuery extends React.Component {
    componentDidMount() {
        const { actions, selectedKey,location } = this.props;
        // 将组件动作接口开放至全局
        let params = {};
        if(JSON.stringify(location.query)==="{}"){
            params= {};
        }else{
            params={...location.query,fromType:1};
        }
        window.crm_action_contractQuery = actions;
        actions.setNowRouterCmpath('contractQuery');
        actions.initDatas(params);
        actions.doSearch(params);
    }
    componentWillReceiveProps(nextProps) {

    }
    shouldComponentUpdate(nextProps, nextState) {
        return !is(this.props.title, nextProps.title) ||
            !is(this.props.dataKey, nextProps.dataKey) ||
            !is(this.props.tabDatas, nextProps.tabDatas) ||
            !is(this.props.conditionInfo, nextProps.conditionInfo) ||
            !is(this.props.showSearchAd, nextProps.showSearchAd) ||
            !is(this.props.searchParamsAd, nextProps.searchParamsAd) ||
            !is(this.props.loading, nextProps.loading) ||
            !is(this.props.comsWeaTable, nextProps.comsWeaTable) ||
            !is(this.props.orderFields, nextProps.orderFields) ||
            !is(this.props.isShowDialog, nextProps.isShowDialog) ||
            !is(this.props.dialogLoading, nextProps.dialogLoading) ||
            !is(this.props.mainTableInfo, nextProps.mainTableInfo) ||
            !is(this.props.subTable1Info, nextProps.subTable1Info) ||
            !is(this.props.subTable2Info, nextProps.subTable2Info) ||
            !is(this.props.subTable3Info, nextProps.subTable3Info) ||
            !is(this.props.subTable4Info, nextProps.subTable4Info) ||
            !is(this.props.rightMenuInfo, nextProps.rightMenuInfo) ||
            !is(this.props.canEdit, nextProps.canEdit) ||
            !is(this.props.dialogPageType, nextProps.dialogPageType) ||
            !is(this.props.contractId, nextProps.contractId) ||
            !is(this.props.isClearNowPageStatus, nextProps.isClearNowPageStatus)||
            !is(this.props.modleSelectTabKey,nextProps.modleSelectTabKey)||
            !is(this.props.shareList,nextProps.shareList)||
            !is(this.props.hasTab,nextProps.hasTab)||
            !is(this.props.exchangeList,nextProps.exchangeList)||
            !is(this.props.infoFields,nextProps.infoFields)||
            !is(this.props.status,nextProps.status)

    }
    componentWillUnmount() {
        const { actions, isClearNowPageStatus } = this.props;
        actions.unmountClear(isClearNowPageStatus);
        actions.isClearNowPageStatus(false);
    }
    render() {
        const { actions,location, loading, title, dataKey, tabDatas, selectedKey, showSearchAd, searchParamsAd, comsWeaTable,isShowDialog,dialogLoading,
            mainTableInfo,subTable1Info,subTable2Info,subTable3Info,subTable4Info,rightMenuInfo,canEdit,dialogPageType,modleSelectTabKey,hasTab,shareList,exchangeList,infoFields,status} = this.props;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        const dialogBottomBtns = [
            (<Button type="ghost" onClick={this.closeDialog.bind(this)}>关闭</Button>)
        ]
        let modleTabDatas = [
            {title:'基本信息',key:"1"},
            {title:'相关交流',key:"2"},
            {title:'共享设置',key:"3"},
        ];
      
        return (
            <div className="crm-top-req" style={{height:"100%"}}>
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                {
                    JSON.stringify(location.query)==="{}" &&
                        <WeaFormmodeTop
                            title={title}
                            loading={loading || loadingTable}
                            icon={<i className='icon-coms-crm' />}
                            iconBgcolor='#96358a'
                            selectedKey={selectedKey}
                            buttons={[]}
                            buttonSpace={10}
                            showDropIcon={true}
                            dropMenuDatas={this.getRightMenu()}
                            onDropMenuClick={this.onRightMenuClick.bind(this)}
                            buttonsAd={this.getTabButtonsAd()}  //高级搜索底部button
                            searchType={['base', 'advanced']}
                            searchsBaseValue={searchParamsAd.get('name')} //外部搜索框默认初始值
                            setShowSearchAd={bool => { actions.setShowSearchAd(bool) }}
                            hideSearchAd={false}
                            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                            showSearchAd={showSearchAd}
                            tabDatas={tabDatas.toJS()}
                            onChange={this.changeTab.bind(this)}
                            onSearch={v => { actions.doSearch() }}
                            onSearchChange={v => { actions.saveOrderFields({ name: { name: 'name', value: v } }) }}
                        >
               
                    </WeaFormmodeTop>
                }
                    <WeaTable
                        sessionkey={dataKey}
                        hasOrder={true}
                        needScroll={false}
                        onOperatesClick={this.onOperatesClick.bind(this)}
                    />
                </WeaRightMenu>
                <WeaDialog title={dialogPageType =="add"? "新建合同信息":"查看合同信息"} icon='icon-coms-crm' iconBgcolor='#96358a' visible={isShowDialog} style={{ width: 1050, height: 600 }} onCancel={this.closeDialog.bind(this)} buttons={dialogBottomBtns}>
                    <WeaReqTop 
                        title={"合同信息"}
                        loading={dialogLoading}
                        icon={<i className='icon-coms-crm' />}
                        iconBgcolor='#96358a'
                        buttons={this.getDialogTopBtns()}
                        buttonSpace={10}
                        showDropIcon={true}
                        tabDatas={hasTab ? modleTabDatas :[]}
                        selectedKey={modleSelectTabKey}
                        onChange={this.modalChangeData.bind(this)}
                    >
                    </WeaReqTop>
                    
                        <div style={{ width: "100%", height: "522px",overflowX:"hidden"}}>
                        {
                            modleSelectTabKey == "1" &&
                            <WeaRightMenu datas={this.getDialogRightMenu(rightMenuInfo.toJS())} onClick={this.onDialogRightMenuClick.bind(this)}>
                                <ContractInfo all={this.props} edit={dialogPageType} infoField={infoFields} actions={actions} mainTableInfo={mainTableInfo.toJS()} subTable1={subTable1Info.toJS()} subTable2 = {subTable2Info.toJS()} subTable3={subTable3Info.toJS()} subTable4 = {subTable4Info.toJS()}/>
                            </WeaRightMenu>
                        }
                        {
                            modleSelectTabKey == "2" &&
                            <RelateCommunication ref="RelateCommunication" datas={exchangeList} actions={actions} all={this.props}/>
                        }
                        {
                            modleSelectTabKey == "3" &&
                            <WeaRightMenu datas={this.contractShareRightMenu()} onClick={this.contractShareRightMenuClick.bind(this)}>
                                <ContractShare  ref="contractShare" all={this.props} data={shareList.toJS()} actions={actions} />
                            </WeaRightMenu>
                            
                        }
                        </div>
                </WeaDialog>
            </div>
        )
    }
    
    closeDialog(){
        const { actions } = this.props;
        actions.closeDialog();
    }
   
    changeTab(selectedKey) {
        const { actions } = this.props;
        actions.changeTab(selectedKey);
        actions.doSearch();
    }
    getRightMenu() {
        const {location} = this.props;
        let btns = [];
        {
            JSON.stringify(location.query)==="{}" &&
            btns.push({
                icon: <i className='icon-coms-search' />,
                content: '搜索',
                key:0
            });
        }
        {
            JSON.stringify(location.query) !=="{}" &&
            btns.push({
                icon: <i className='icon-coms-Add-to ' />,
                content: '新建',
                key:2
            });
        }
        btns.push({
            icon: <i className='icon-coms-Custom ' />,
            content: '显示定制列',
            key:1
        });
        btns.push({
            icon: <i className='icon-coms-Collection' />,
            content: '收藏',
            key:3
        });
        btns.push({
            icon: <i className='icon-coms-help ' />,
            content: '帮助',
            key:4
        });
        return btns
    }
    onRightMenuClick(key) {
        const { actions, comsWeaTable, dataKey,location:{query} } = this.props;
        const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
        if (key == '0') {
            actions.doSearch();
            actions.setShowSearchAd(false);
        }
        if (key == '1') {
            actions.setColSetVisible(dataKey, true);
            actions.tableColSet(dataKey, true);
        }
        if (key == '2') {   //新建合同
            actions.getContractInfo({operation:"add",crmId:query.customerId},"1",false);
        }
    }
    contractShareRightMenu(){
        let btns = [];
        btns.push({
            icon: <i className='icon-coms-Preservation' />,
            content: '保存'
        });
        return btns
    }
    getDialogRightMenu(rightMenuInfo) {
        let items = [];
        rightMenuInfo.map((item, index) => {
            items.push({
                icon: <i className={item.icon}/>,
                content:item.content,
                key:item.key
            });
        });
        return items;
    }
    contractShareRightMenuClick(key){
        const {actions,shareData,shareList,contractId} = this.props;
        const _shareData = shareData.toJS();
        let addshareList = [];
        let oldArr =(function(arr){
                let idArr =[];
                for(let i=0;i<arr.length;i++){
                    idArr.push(arr[i].dataId);
                }
                return idArr;
            })(shareList.toJS());
        let lastArr = [];
        if (key == '0') {
            if(!is(shareData,shareList)){
                for(let i=0;i<_shareData.length;i++){
                    if(!_shareData[i].dataId){
                        addshareList.push(_shareData[i]);
                    }else{
                        lastArr.push(_shareData[i].dataId);
                    }
                }

                lastArr.map(key=>{
                    oldArr = oldArr.filter(data => data !== key);
                });
               actions.contractShareSave({contractId:contractId,deleteIds:`${oldArr}`,shareList:JSON.stringify(addshareList)});
            }else{
                actions.contractShareSave({contractId:contractId,deleteIds:"",shareList:[]});
            }
        }
    }
    onDialogRightMenuClick(key) {
        const {actions,contractId,hasTab} = this.props;
        if (key == '2') {   //签单
            actions.sign(contractId,"rightmenu");
        }
        if(key == "3"){  //执行完成
            actions.complete(contractId,"rightmenu");
         }
        if (key == '8') {  //重新打开
            actions.statusBack(contractId,"rightmenu");
        }
        if (key == '6') {   //共享设置
            actions.getContractShareList({contractId:contractId},"3",true);
        }
        if(key == "0"){  //编辑
            actions.editInfo(contractId);
         }
         if(key == "1"){  //提交审批
            actions.approveInfo(contractId,"rightmenu");
         }
         if(key == "7"){  //保存
            actions.saveInfo(contractId)
         }
         if(key == "9"){  //返回
            actions.getContractInfo({contractId:contractId,operation:"view"},"1",hasTab);
         }
    }
    getTabButtonsAd() {
        const { actions ,form} = this.props;
        return [
            (<Button type="primary" onClick={() => { actions.doSearch(); actions.setShowSearchAd(false) }}>搜索</Button>),
            (<Button type="ghost" onClick={() => { actions.saveOrderFields({}); }}>重置</Button>),
            (<Button type="ghost" onClick={() => { actions.setShowSearchAd(false) }}>取消</Button>)
        ]
    }
    getSearchs() {
        const { conditionInfo } = this.props;
        let conditionAttr = [];
        conditionInfo.map((item, index) => {
            conditionAttr.push(
                <WeaSearchGroup needTigger={true} title={this.getTitle(index)} showGroup={this.isShowFields(index)} items={this.getFields(index)} />
            );
        });
        return conditionAttr;
    }
    getTitle(index = 0) {
        const { conditionInfo } = this.props;
        return !isEmpty(conditionInfo.toJS()) && conditionInfo.toJS()[index].title;
    }
    isShowFields(index = 0) {
        const { conditionInfo } = this.props;
        return !isEmpty(conditionInfo.toJS()) && conditionInfo.toJS()[index].defaultshow;
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
        const { conditionInfo } = this.props;
        const fieldsData = !isEmpty(conditionInfo.toJS()) && conditionInfo.toJS()[index].items;
        let items = [];
        forEach(fieldsData, (field) => {
            items.push({
                com: (<FormItem
                    label={`${field.label}`}
                    labelCol={{ span: `${field.labelcol}` }}
                    wrapperCol={{ span: `${field.fieldcol}` }}>
                    {WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                </FormItem>),
                colSpan: 1
            })
        });
        return items;
    }
    getDialogTopBtns() {
        const { actions,contractId,canEdit,dialogPageType ,modleSelectTabKey} = this.props;
        let btns = [];
        if(modleSelectTabKey == "1"){
            if(dialogPageType == "view"){
                if(canEdit){
                    btns.push((<Button type="primary" onClick={() => { actions.editInfo(contractId)}}>编辑</Button>));
                }
            }else if(dialogPageType == "edit"){
                btns.push((<Button type="primary" onClick={() => { actions.saveInfo(contractId)}}>保存</Button>));
            }
        }
        {modleSelectTabKey == "3" &&  btns.push((<Button type="primary" onClick={() =>{this.contractShareRightMenuClick("0")}}>保存</Button>));}
        {dialogPageType == "add" &&  btns.push((<Button type="primary" onClick={() =>{actions.saveInfo()}}>保存</Button>));}
        return btns;
    }
    onOperatesClick(record,index,operate,flag){
        //console.log(record,index,operate,flag);
        const {actions} = this.props;
        if(flag=="6"){  //设置共享
            actions.getContractShareList({contractId:record.randomFieldId},"3",true);
        }
        if(flag=="5"){   //相关交流
           actions.getExchangeList({contractId:record.randomFieldId},"2",true);
        }
        if(flag=="4"){   //合同打开
           actions.getContractInfo({contractId:record.randomFieldId,operation:record.status == '2' ? "edit" : "view"},"1",true);
            // actions.getContractInfo(record.randomFieldId,"1",true,record.status);
         }
         if(flag == "2"){  //签单
            actions.sign(record.randomFieldId,"operate");
         }
         if(flag == "3"){  //执行完成
            actions.complete(record.randomFieldId,"operate");
         }
         if(flag == "1"){  //提交审批
            actions.approveInfo(record.randomFieldId,"operate");
         }
         if(flag == "0"){  //编辑
           actions.getContractInfo({contractId:record.randomFieldId,operation:"edit"},"1",false);
            // actions.getContractInfo(record.randomFieldId,"1",false,record.status);
         }
    }
    modalChangeData(key){
        const {actions} =this.props;
        actions.changeModalTab(key);
    }
}


//form 表单与 redux 双向绑定
ContractQuery = createForm({
    onFieldsChange(props, fields) { 
        props.actions.saveOrderFields({ ...props.orderFields.toJS(), ...fields });
    },
    mapPropsToFields(props) {
        return props.orderFields.toJS();
    }
})(ContractQuery);

function mapStateToProps(state) {
    const { crmcontractQuery, comsWeaTable } = state;
    return {
        loading: crmcontractQuery.get('loading'),
        title: crmcontractQuery.get('title'),
        dataKey: crmcontractQuery.get('dataKey'),
        conditioninfo: crmcontractQuery.get('conditioninfo'),
        selectedKey: crmcontractQuery.get('selectedKey'),
        orderFields: crmcontractQuery.get('orderFields'),
        showSearchAd: crmcontractQuery.get('showSearchAd'),
        searchParamsAd: crmcontractQuery.get('searchParamsAd'),
        tabDatas: crmcontractQuery.get('tabDatas'),
        conditionInfo: crmcontractQuery.get('conditionInfo'),
        isClearNowPageStatus: crmcontractQuery.get("isClearNowPageStatus"),
        isShowDialog: crmcontractQuery.get("isShowDialog"),
        dialogLoading: crmcontractQuery.get("dialogLoading"),
        mainTableInfo: crmcontractQuery.get("mainTableInfo"),
        subTable1Info: crmcontractQuery.get("subTable1Info"),
        subTable2Info: crmcontractQuery.get("subTable2Info"),
        subTable3Info: crmcontractQuery.get("subTable3Info"),
        subTable4Info: crmcontractQuery.get("subTable4Info"),
        rightMenuInfo: crmcontractQuery.get("rightMenuInfo"),
        canEdit: crmcontractQuery.get("canEdit"),
        contractId: crmcontractQuery.get("contractId"),
        dialogPageType: crmcontractQuery.get("dialogPageType"),
        modleSelectTabKey:crmcontractQuery.get('modleSelectTabKey'),
        hasTab:crmcontractQuery.get('hasTab'),
        shareData:crmcontractQuery.get('shareData'),
        shareList:crmcontractQuery.get('shareList'),
        exchangeList:crmcontractQuery.get('exchangeList'),
        infoFields:crmcontractQuery.get('infoFields'),
        status:crmcontractQuery.get('status'),
        //table
        comsWeaTable: comsWeaTable//绑定整个table
    } 
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({ ...ContractQueryAction, ...WeaTableAction }, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ContractQuery);